<template>
  <div style="max-width: 900px; margin: 0 auto;">
    <h2 style="text-align: center; margin: 30px 0;">入院评估单</h2>
    <div style="display: flex; justify-content: space-between; margin-bottom: 30px; font-size: 16px;">
      <div>姓名：{{ item.name }}</div>
      <div>性别：{{ item.sex == 1 ? '男' : '女' }}</div>
      <div>年龄：{{ item.age }}</div>
      <div>科别：{{ item.officeCode }}</div>
      <div>床号：{{ item.bedCode }}</div>
    </div>
    <el-form :model="form" label-width="120px"
      style="background: #fff; padding: 30px 40px; border-radius: 10px; box-shadow: 0 2px 8px #f0f1f2;">
      <el-form-item label="入院转入方式" style="margin-bottom: 18px;">
        <el-radio-group v-model="form.inType" style="display: flex; gap: 40px;">
          <el-radio value="步行" label="步行" />
          <el-radio value="轮椅" label="轮椅" />
          <el-radio value="平车" label="平车" />
          <el-radio value="其他" label="其他" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="意识" style="margin-bottom: 18px;">
        <el-radio-group v-model="form.sense" style="display: flex; gap: 40px;">
          <el-radio value="清醒" label="清醒" />
          <el-radio value="嗜睡" label="嗜睡" />
          <el-radio value="模糊" label="模糊" />
          <el-radio value="昏睡" label="昏睡" />
          <el-radio value="昏迷" label="昏迷" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="语言表达" style="margin-bottom: 18px;">
        <el-radio-group v-model="form.language" style="display: flex; gap: 40px;">
          <el-radio value="正常" label="正常" />
          <el-radio value="含糊不清" label="含糊不清" />
          <el-radio value="失语" label="失语" />
          <el-radio value="不能表达" label="不能表达" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动能力" style="margin-bottom: 18px;">
        <el-radio-group v-model="form.activity" style="display: flex; gap: 40px;">
          <el-radio value="行动正常" label="行动正常" />
          <el-radio value="协助活动" label="协助活动" />
          <el-radio value="使用助行器" label="使用助行器" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label=" " style="margin-bottom: 18px;">
        <el-radio-group v-model="form.activity" style="display: flex; gap: 40px;">
          <el-radio value="残肢" label="残肢" />
          <el-radio value="卧床" label="卧床" />
          <el-radio value="其他" label="其他" />
          <el-radio value="跌倒高危" label="跌倒高危" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="视力情况" style="margin-bottom: 18px;">
        <div style="display: flex; align-items: center; gap: 40px; flex-wrap: wrap;">
          <div style="display: flex; align-items: center; min-width: 200px;">
            <span style="font-weight: bold; width: 50px;">左眼：</span>
            <el-radio-group v-model="form.lefteye" style="display: flex; gap: 20px;">
              <el-radio value="清晰" label="清晰" />
              <el-radio value="失明" label="失明" />
              <el-radio value="模糊" label="模糊" />
            </el-radio-group>
          </div>
          <div style="display: flex; align-items: center; min-width: 200px;">
            <span style="font-weight: bold; width: 50px;">右眼：</span>
            <el-radio-group v-model="form.righteye" style="display: flex; gap: 20px;">
              <el-radio value="清晰" label="清晰" />
              <el-radio value="失明" label="失明" />
              <el-radio value="模糊" label="模糊" />
            </el-radio-group>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="听力情况" style="margin-bottom: 18px;">
        <div style="display: flex; align-items: center; gap: 40px; flex-wrap: wrap;">
          <div style="display: flex; align-items: center; min-width: 200px;">
            <span style="font-weight: bold; width: 50px;">左耳：</span>
            <el-radio-group v-model="form.leftear" style="display: flex; gap: 20px;">
              <el-radio value="清晰" label="清晰" />
              <el-radio value="失聪" label="失聪" />
              <el-radio value="模糊" label="模糊" />
            </el-radio-group>
          </div>
          <div style="display: flex; align-items: center; min-width: 200px;">
            <span style="font-weight: bold; width: 50px;">右耳：</span>
            <el-radio-group v-model="form.rightear" style="display: flex; gap: 20px;">
              <el-radio value="清晰" label="清晰" />
              <el-radio value="失聪" label="失聪" />
              <el-radio value="模糊" label="模糊" />
            </el-radio-group>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="排泄" style="margin-bottom: 18px;">
        <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
          <div style="display: flex; align-items: center; min-width: 300px;">
            <span style="font-weight: bold; width: 50px;">小便：</span>
            <el-radio-group v-model="form.minExcrete" style="display: flex; gap: 20px;">
              <el-radio value="正常" label="正常" />
              <el-radio value="失禁" label="失禁" />
              <el-radio value="尿频" label="尿频" />
              <el-radio value="尿潴留" label="尿潴留" />
              <el-radio value="留置导尿管" label="留置导尿管" />
            </el-radio-group>
          </div>
          <div style="display: flex; align-items: center; min-width: 300px;">
            <span style="font-weight: bold; width: 50px;">大便：</span>
            <el-radio-group v-model="form.maxExcrete" style="display: flex; gap: 20px;">
              <el-radio value="正常" label="正常" />
              <el-radio value="失禁" label="失禁" />
              <el-radio value="腹泻" label="腹泻" />
              <el-radio value="便秘" label="便秘" />
              <el-radio value="肠造口" label="肠造口" />
            </el-radio-group>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="签名" style="margin-bottom: 18px;">
        <div style="display: flex; flex-direction: column;">
          <canvas ref="signCanvas" width="300" height="80"
            style="border:1px solid #ccc; border-radius: 4px; background: #fff;"></canvas>
          <div style="margin-top: 8px;">
            <el-button size="small" @click="clearSignature">清除</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item style="text-align: center;">
        <el-button type="primary" @click="onSubmit" style="width: 100px;">保存</el-button>
        <el-button @click="onCancel" style="width: 100px; margin-left: 30px;">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import http from '@/api/http';
import { ElMessage } from 'element-plus'  // 删除未使用的 ElMention
import { reactive, ref, onMounted } from 'vue'  // 删除未使用的 computed
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 简化 item 的获取
const item = JSON.parse(typeof route.query.item === 'string' ? route.query.item : '{}');

const form = ref({
    patientCode: item.patientCode,
    nurseCode: Math.random().toString(36).slice(2, 10),
    inType: '',
    sense: '',
    language: '',
    activity: '',
    lefteye: '',
    righteye: '',
    leftear: '',
    rightear: '',
    maxExcrete: '',
    minExcrete: '',
    signUrl: '',
    vision: '',
    hearing: '',
});

// Canvas 相关变量
const signCanvas = ref<HTMLCanvasElement | null>(null);
let ctx: CanvasRenderingContext2D | null = null;
let drawing = false;

// Canvas 初始化和事件绑定
onMounted(() => {
    if (!signCanvas.value) return;
    ctx = signCanvas.value.getContext('2d');
    if (!ctx) return;
    
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    // 事件监听器
    const canvas = signCanvas.value;
    canvas.addEventListener('mousedown', startDrawing as EventListener);
    canvas.addEventListener('mousemove', draw as EventListener);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mouseout', stopDrawing);
    canvas.addEventListener('touchstart', startTouch as EventListener);
    canvas.addEventListener('touchmove', moveTouch as EventListener);
    canvas.addEventListener('touchend', stopDrawing);
});

// 绘图相关函数
function startDrawing(e: MouseEvent) {
    if (!ctx || !signCanvas.value) return;
    drawing = true;
    const rect = signCanvas.value.getBoundingClientRect();
    ctx.beginPath();
    ctx.moveTo(e.clientX - rect.left, e.clientY - rect.top);
}

function draw(e: MouseEvent) {
    if (!drawing || !ctx || !signCanvas.value) return;
    const rect = signCanvas.value.getBoundingClientRect();
    ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top);
    ctx.stroke();
}

function stopDrawing() {
    drawing = false;
}

// 触摸事件处理
function startTouch(e: TouchEvent) {
    if (!ctx || !signCanvas.value) return;
    e.preventDefault();
    drawing = true;
    const rect = signCanvas.value.getBoundingClientRect();
    const touch = e.touches[0];
    ctx.beginPath();
    ctx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top);
}

function moveTouch(e: TouchEvent) {
    if (!drawing || !ctx || !signCanvas.value) return;
    e.preventDefault();
    const rect = signCanvas.value.getBoundingClientRect();
    const touch = e.touches[0];
    ctx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);
    ctx.stroke();
}

// 工具函数
function clearSignature() {
    if (!ctx || !signCanvas.value) return;
    ctx.clearRect(0, 0, signCanvas.value.width, signCanvas.value.height);
    form.value.signUrl = '';
}

// 提交处理
const onSubmit = async () => {
    if (!signCanvas.value) {
        ElMessage.warning('请先签名');
        return;
    }

    const imageData = ctx?.getImageData(0, 0, signCanvas.value.width, signCanvas.value.height).data;
    if (!imageData || imageData.every(pixel => pixel === 0 || pixel === 255)) {
        ElMessage.warning('签名不能为空，请签名后再提交');
        return;
    }

    try {
        const signatureDataUrl = signCanvas.value.toDataURL('image/png');
        const base64Data = signatureDataUrl.split(',')[1];
        
        // 上传签名图片
        const newimgurl = await http.post('/api/InAssessController/UpdateImg', base64Data);
        
        // 更新表单数据
        form.value.vision = `左眼：${form.value.lefteye} 右眼：${form.value.righteye}`;
        form.value.hearing = `左耳：${form.value.leftear} 右耳：${form.value.rightear}`;
        form.value.signUrl = newimgurl;

        // 提交表单
        await http.post('/api/InAssessController/AddInAssess', form.value);
        
        ElMessage.success('保存成功');
        router.push({
            path: '/ShowInAssess',
            query: {
                name: item.name,
                sex: item.sex,
                age: item.age,
                officeCode: item.officeCode,
                bedCode: item.bedCode
            }
        });
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请重试');
    }
};

const onCancel = () => router.push('/InAssessButton');
</script>